﻿using System;
using System.IO;
using System.Net;
using System.Xml.Serialization;
using LetsDoIt.Common;
using Newtonsoft.Json;

namespace LetsDoIt.BO
{
    /// <summary>
    /// factory class used for comunication with web service - authorization
    /// </summary>
	public static class AuthServiceFactory
	{
        /// <summary>
        /// Valida user on the server
        /// </summary>
        /// <param name="user">user name</param>
        /// <param name="md5pass">md5 hashed pass</param>
        /// <returns>true if is authenticated</returns>
		public static bool ValidateUser(string user, string md5pass)
		{
			bool result = false;

			try
			{
				HttpWebRequest webReq = HttpWebRequest.Create(WebServiceNames.WS_BASE_ADDRESSS + string.Format(WebServiceNames.AUTH_ADDRESS, user, md5pass)) as HttpWebRequest;
				if (webReq != null)
				{
					webReq.AllowAutoRedirect = true;
					webReq.AllowWriteStreamBuffering = true;
					webReq.Method = "GET";
					webReq.ContentType = "text/xml";

					WebResponse webResponse = webReq.GetResponse();

					string contents = string.Empty;
					using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
					{
						contents = reader.ReadToEnd();
						webResponse.Close();
					}

					XmlSerializer ser = new XmlSerializer(typeof(bool));
					result = (bool)ser.Deserialize(new StringReader(contents));
				}
			}
			catch (WebException ex)
			{
				//Log error
				HttpWebResponse res = (HttpWebResponse)ex.Response;
				if (res != null)
				{
					HttpStatusCode status = res.StatusCode;
					string contentResponse;
					using (Stream stm = res.GetResponseStream())
					{
						using (StreamReader reader = new StreamReader(stm))
						{
							contentResponse = reader.ReadToEnd();
						}
					}
					ErrorDetail detail = JsonConvert.DeserializeObject<ErrorDetail>(contentResponse);
					if (detail != null)
						Program.Log.Error(ex.Status + " " + detail.Detail);
				}
				else
				{
					Program.Log.Error(ex.ToString());
				}
			}
			catch (Exception ex)
			{
				//Log error
				Program.Log.Error(ex.ToString());
			}

			return result;
		}

        /// <summary>
        /// Retrieves user specific "salt" string from server
        /// </summary>
        /// <param name="user">userename</param>
        /// <returns>"salt" string to be used with password and md5 hashing to generate an md5 hash password</returns>
        public static string GetUserSalt(string user)
        {
            string result = string.Empty;

            try
            {
                HttpWebRequest webReq = HttpWebRequest.Create(WebServiceNames.WS_BASE_ADDRESSS + string.Format(WebServiceNames.USER_SALT_ADDRESS, user)) as HttpWebRequest;
                if (webReq != null)
                {
                    webReq.AllowAutoRedirect = true;
                    webReq.AllowWriteStreamBuffering = true;
                    webReq.Method = "GET";
                    webReq.ContentType = "text/xml";

                    WebResponse webResponse = webReq.GetResponse();

                    string contents = string.Empty;
                    using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
                    {
                        contents = reader.ReadToEnd();
                        webResponse.Close();
                    }

                    XmlSerializer ser = new XmlSerializer(typeof(string));
                    result = (string)ser.Deserialize(new StringReader(contents));
                }
            }
            catch (WebException ex)
            {
                //Log error
                HttpWebResponse res = (HttpWebResponse)ex.Response;
                if (res != null)
                {
                    HttpStatusCode status = res.StatusCode;
                    string contentResponse;
                    using (Stream stm = res.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stm))
                        {
                            contentResponse = reader.ReadToEnd();
                        }
                    }
                    ErrorDetail detail = JsonConvert.DeserializeObject<ErrorDetail>(contentResponse);
                    if (detail != null)
                        Program.Log.Error(ex.Status + " " + detail.Detail);
                }
                else
                {
                    Program.Log.Error(ex.ToString());
                }
            }
            catch (Exception ex)
            {
                //Log error
                Program.Log.Error(ex.ToString());
            }

            return result;
        }



        /// <summary>
        /// Gets an installation ID from web service
        /// </summary>
        /// <returns>installation ID offered by the server</returns>
        public static string GetInstallationId()
        {
            string result = string.Empty;

            try
            {
                HttpWebRequest webReq = HttpWebRequest.Create(WebServiceNames.WS_BASE_ADDRESSS + WebServiceNames.INSTALL_ID_ADDRESS) as HttpWebRequest;
                if (webReq != null)
                {
                    webReq.AllowAutoRedirect = true;
                    webReq.AllowWriteStreamBuffering = true;
                    webReq.Method = "GET";
                    webReq.ContentType = "text/xml";

                    WebResponse webResponse = webReq.GetResponse();

                    string contents = string.Empty;
                    using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
                    {
                        contents = reader.ReadToEnd();
                        webResponse.Close();
                    }

                    XmlSerializer ser = new XmlSerializer(typeof(string));
                    result = (string)ser.Deserialize(new StringReader(contents));
                }
            }
            catch (WebException ex)
            {
                //Log error
                HttpWebResponse res = (HttpWebResponse)ex.Response;
                if (res != null)
                {
                    HttpStatusCode status = res.StatusCode;
                    string contentResponse;
                    using (Stream stm = res.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stm))
                        {
                            contentResponse = reader.ReadToEnd();
                        }
                    }
                    ErrorDetail detail = JsonConvert.DeserializeObject<ErrorDetail>(contentResponse);
                    if (detail != null)
                        Program.Log.Error(ex.Status + " " + detail.Detail);
                }
                else
                {
                    Program.Log.Error(ex.ToString());
                }
            }
            catch (Exception ex)
            {
                //Log error
                Program.Log.Error(ex.ToString());
            }

            return result;
        }
	}
}
